/*
	EnemyRespawn.cs
	Checks if player is in range, if so enemy is instantiated. When player moves out of range the 
	prefab is destroyed. Prevents repeated calls to the enemys AI sripts, improving performance
*/

using UnityEngine;
using System.Collections;


public class EnemyRespawn : MonoBehaviour
{
	public float spawnRange = 0.0f;
	public string gizmoName;
	public GameObject enemyPrefab;
	
	//Cache variables used to improve performance
	private Transform player;
	private GameObject currentEnemy;
	private bool wasOutside = true;
	
	void Start()
	{
		player = GameObject.FindWithTag("Player").transform;
	}
	
	//Called every game cycle
	void Update()
	{
		//Distance to player
		float distanceToPlayer = Vector3.Distance(transform.position, player.position);
		
		//Is player in range?
		if(distanceToPlayer < spawnRange)
		{
			//In range. Instantiate enemy prefab at location
			if(!currentEnemy && wasOutside)
			{
				currentEnemy = (GameObject)Instantiate(enemyPrefab, transform.position, transform.rotation);
			}
			
			//Player is now inside range, so set flag to prevent multiple prefabs
			wasOutside = false;
		}
		
		//player is out of range
		else
		{
			//Is player leaving the sphere of influence while prefab is active?
			if(currentEnemy && !wasOutside)
			{
				//Kill prefab
				Destroy(currentEnemy);
			}	
			
			wasOutside = true;
		}
	}
	
	void OnDrawGizmos()
	{
		Gizmos.color = new Color(1,1,1,1);
		
		//Check help to determine where icon should be stored
		Gizmos.DrawIcon(transform.position, gizmoName + ".psd");
	}
	
	void OnDrawGizmosSelected()
	{
		Gizmos.color = new Color(0,1,1);
		Gizmos.DrawWireSphere(transform.position, spawnRange);
	}
}